package com.ssh.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import com.mongodb.util.ThreadUtil;

/**
 * 非阻塞socket应用实例(没用到selector)
 * 
 * @author nexus
 * 
 */
public class NonBlockingSocketChannelTest {
	private static final String HELLO = "hello,welcom to visit this socket;";

	public static void main(String[] args) throws IOException {
		ByteBuffer buffer = ByteBuffer.wrap(HELLO.getBytes());
		// 这个channel并没有实现读写操作，只是监听用的
		ServerSocketChannel sschannel = ServerSocketChannel.open();
		sschannel.socket().bind(new InetSocketAddress(1234));
		sschannel.configureBlocking(false);

		System.out.println("wating for connections...");
		while (true) {
			SocketChannel schannel = sschannel.accept();
			if (schannel != null) {
				System.out.println("incoming from ++++"
						+ schannel.socket().getRemoteSocketAddress()
						+ schannel.socket().toString());
				buffer.rewind();
				schannel.write(buffer);

				ThreadUtil.sleep(200);
				schannel.close();
				System.out.println("-----already closed-----");
			}

		}
	}
}
